<template>
  <div class="content-box">
    <el-form
      ref="flowFormRef"
      :model="flowFormData"
      :rules="fromRules"
      label-width="180px"
      class="form__content"
    >
      <template v-if="nodeDefId === 'ACT_011'">
        <el-form-item label="开工材料" prop="defaultFileList">
          <ecm-upload
            :disabled="!isEdit"
            :files="flowFormData.defaultFileList"
            @set-file="
              fileList => {
                handleChange(fileList, '1');
              }
            "
          ></ecm-upload>
          <el-text line-clamp="6">
            需上传的材料清单列表:<br />
            1、保险<br />
            2、保函<br />
            3、公司证照（营业执照及安全生产许可证）<br />
            4、项目经理及主要管理人员证照资料<br />
            5、安全相关资料（包括但不限于施工单位安全生产责任承诺书、施工人员登记表）<br />
            6、其他相关资料
          </el-text>
        </el-form-item>
        <el-form-item label="开工材料简述" prop="rectificationInfo">
          <el-input
            :disabled="!isEdit"
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="flowFormData.rectificationInfo"
          ></el-input>
        </el-form-item>
      </template>

      <template v-else>
        <el-form-item label="材料复核" prop="supervisorAccOpinion">
          <el-radio-group v-model="flowFormData.supervisorAccOpinion">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="0">未通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="材料复核意见" prop="content">
          <el-input
            :disabled="!isEdit"
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="flowFormData.content"
          ></el-input>
        </el-form-item>
      </template>
    </el-form>

    <div class="form__footer right-align-box" v-if="isEdit">
      <el-button @click="handleBack">取 消</el-button>
      <el-button
        type="primary"
        @click="handleTransfer"
        v-if="nodeDefId !== 'ACT_010'"
        >转 办</el-button
      >
      <el-button
        type="danger"
        @click="handleSubmit('0')"
        v-if="['ACT_015', 'ACT_013'].includes(nodeDefId)"
        >驳 回</el-button
      >
      <el-button
        type="danger"
        @click="handleReject"
        v-else-if="nodeDefId !== 'ACT_010'"
        >驳 回</el-button
      >
      <el-button type="primary" @click="inform"> 知 会</el-button>
      <el-button type="primary" @click="handleSave">保 存</el-button>
      <el-button type="primary" @click="handleSubmit('1')">提 交</el-button>
    </div>

    <el-dialog
      title="选择人员"
      v-model="dialogVisibleTransferAdd"
      width="920px"
    >
      <add-user
        v-model:dialogVisibleTransferAdd="dialogVisibleTransferAdd"
        :currentUsers="acceptUsers"
        :isSingle="true"
        @emitAddUser="showNextJump"
      />
    </el-dialog>

    <el-dialog
      title="驳回"
      v-model="dialogVisible"
      destroy-on-close
      width="600px"
    >
      <reject-view
        v-model:dialogVisible="dialogVisible"
        :taskId="formBaseInfo.taskId"
        :formBaseInfo="formBaseInfo"
        :module="module"
      />
    </el-dialog>

    <!-- 最后一步驳回到指定节点 -->
    <el-dialog
      title="驳回"
      v-model="dialogVisibleLastNode"
      destroy-on-close
      width="600px"
    >
      <el-form
        :model="rejectFormData"
        ref="rejectFormRef"
        :rules="rejectRules"
        label-position="top"
        label-width="80px"
        class="content"
      >
        <el-form-item label="驳回意见" prop="remark">
          <el-input
            v-model.trim="rejectFormData.remark"
            type="textarea"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-row justify="end" class="form__footer">
        <el-button @click="dialogVisibleLastNode = false">取 消</el-button>
        <el-button type="primary" @click="toSubmit">确 定</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, watch, ref, defineEmits, watchEffect } from "vue";
import { useRoute } from "vue-router";
import AddUser from "../../../projectsA/acceptance/concealed/components/dialog/AddUser.vue";
import RejectView from "../dialog/RejectView.vue";
import { storageLocal } from "/@/utils/storage";
import { startWorkFlowSubmit } from "/@/api/construction";
import { flowNotify } from "/@/api/work";
import {
  // projectTeamList,
  getApproveHandlerId,
  transfer,
  postSaveDraft,
  getDraft
} from "/@/api/projects";
import { flowTypeObj } from "../../detail/type";
import NotifMessage from "/@/utils/message/notification";
import ecmUpload from "/@/components/ecmUpload/index.vue";
const route = useRoute();
const flowFormRef = ref<HTMLFormElement | null>(null) as any;
const rejectFormRef = ref<HTMLFormElement | null>(null) as any;
const emit = defineEmits(["handleSubmit", "handleBack"]);
const props = defineProps({
  formBaseInfo: {
    type: Object,
    default: () => {}
  },
  module: {
    type: String,
    default: "snap"
  }
});
const formBaseInfo = ref<object>({});
// const initVal = ref(true);
const flowFormData = ref({
  snapshotName: formBaseInfo.value.snapshotName || "",
  content: formBaseInfo.value.content || "",
  snapshotAttachment: formBaseInfo.value.snapshotAttachment || [],
  rectificationAttachment: [],
  partybHandlerInfo: [] as any,
  partybHandlerId: "",
  partybHandlerName: "",
  rectificationInfo: "",
  defaultFileList: [],
  supervisorAccOpinion: "",
  option: []
}); // 待处理信息

const rejectFormData = ref({
  remark: ""
});
const fromRules = ref({
  // rectificationAttachment: [
  //   { required: true, message: "请上传整改说明", trigger: "change" }
  // ],
  // supervisorAccOpinion: [
  //   { required: true, message: "请输入审批意见", trigger: "change" }
  // ],
  // snapshotName: [
  //   { required: true, message: "请填写问题标题", trigger: "change" }
  // ],
  content: [
    { required: true, message: "请填写材料复核意见", trigger: "change" }
  ],
  defaultFileList: [
    { required: true, message: "请上传开工材料", trigger: "change" }
  ]
});
const rejectRules = ref({
  remark: [{ required: true, message: "请输入驳回意见", trigger: "change" }]
});
const dialogVisible = ref(false); // 驳回弹窗是否展示
const dialogVisibleTransferAdd = ref(false); // 选择人员的弹窗是否显示
let dialogVisibleType = ref("submit");
const dialogVisibleLastNode = ref(false);
const acceptUsers = ref([]); // 已选择人员
const addUserInfo = ref<object>({}); // 人员选择器，所选择人员信息
const isEdit = ref(route.query?.mode !== "read");
const nodeDefId = ref(route.query?.nodeDefId);
const instanceId = ref(route.query?.instanceId);
const flowId = ref(route.query?.flowId);
const flowType = ref(route.query?.flowType);
const lastNode = ref("");
const approveHandlerId = ref("");
const nodeList = flowTypeObj[flowType.value].nodeId;
lastNode.value = nodeList[nodeList.length - 1];
let isSubmit = ref(false); // 是否“提交”

const handleChange = (fileList, num) => {
  if (num === "1") {
    flowFormData.value.defaultFileList = fileList;
    flowFormRef.value.clearValidate("defaultFileList");
  } else if (num === "7") {
    flowFormData.value.rectificationAttachment = fileList;
  } else if (num === "6") {
    flowFormData.value.snapshotAttachment = fileList;
    flowFormRef.value.clearValidate("snapshotAttachment");
  }
};

// const onInitFileList = (list: any[]) => {
//   if (!list || !list.length || !list[0]?.fileName) return;
//   const newFileList = list.map(item => {
//     return {
//       name: item?.fileName,
//       response: {
//         data: item,
//         code: 200
//       }
//     };
//   });
//   return newFileList;
// };

//转办
const handleTransfer = async () => {
  dialogVisibleTransferAdd.value = true;
  dialogVisibleType.value = "transfer";
};

// 知会按钮
const inform = () => {
  if (instanceId.value) {
    dialogVisibleTransferAdd.value = true;
    dialogVisibleType.value = "inform";
  } else {
    NotifMessage.info("当前流程还未发起，暂无法知会");
    return;
  }
};

const handleSave = async () => {
  const params = {
    flowId: flowId.value,
    nodeId: nodeDefId.value,
    taskId: formBaseInfo.value?.taskId,
    formJson: JSON.stringify(flowFormData.value)
  };
  const { code, message } = await postSaveDraft(params);
  if (code === 200) {
    NotifMessage.success(message);
  } else {
    NotifMessage.error(message);
  }
};

const getFlowFormData = async () => {
  const { data } = await getDraft(formBaseInfo.value?.taskId);
  if (data?.formJson) {
    flowFormData.value = JSON.parse(data.formJson);
  }
};

// 提交(最后一个节点驳回)
const handleSubmit = async isChargehand => {
  isSubmit.value = true;
  formBaseInfo.value.isChargehand = isChargehand;
  let nodes = flowTypeObj[flowType.value].nodeId;
  // if (nodeDefId.value === nodes[nodes.length - 1]) {
  //最后一个节点不需要选择下一节点处理人
  if (isChargehand === "0") {
    //驳回
    getApproveUserId();
    dialogVisibleLastNode.value = true;
    // const isValid = await new Promise(resolve =>
    //   flowFormRef.value.validate(resolve)
    // );
    // if (!isValid) return;
    // dialogVisibleTransferAdd.value = true;
    // dialogVisibleType.value = "submit";
  } else {
    if (nodeDefId.value === nodes[nodes.length - 1]) {
      const isValid = await new Promise(resolve =>
        flowFormRef.value.validate(resolve)
      );
      if (!isValid) return;
      emitAddUser();
    } else {
      const isValid = await new Promise(resolve =>
        flowFormRef.value.validate(resolve)
      );
      if (!isValid) return;
      dialogVisibleTransferAdd.value = true;
      dialogVisibleType.value = "submit";
    }
  }
  // } else {
  //   const isValid = await new Promise(resolve =>
  //     flowFormRef.value.validate(resolve)
  //   );
  //   if (!isValid) return;
  //   dialogVisibleTransferAdd.value = true;
  //   dialogVisibleType.value = "submit";
  // }
};

const showNextJump = parmas => {
  addUserInfo.value = parmas;
  if (dialogVisibleType.value === "submit") {
    emitAddUser();
  } else if (dialogVisibleType.value === "transfer") {
    //转办
    submitTransfer(parmas);
  } else if (dialogVisibleType.value === "inform") {
    //知会
    submitInform(parmas);
  }
};

//知会
const submitInform = async parmas => {
  const notifys = [];
  const id = parmas?.idList[0].id;
  notifys.push(id);
  const userInfo = storageLocal.getItem("info");
  let params = {
    assignee: userInfo?.userId,
    instanceId: instanceId.value,
    taskId: formBaseInfo.value?.taskId,
    notifys: notifys
  };
  try {
    const { code, message } = await flowNotify(params);
    if (code === 200) {
      NotifMessage.success(message);
      dialogVisibleTransferAdd.value = false;
      handleBack();
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

const emitAddUser = () => {
  dialogVisibleTransferAdd.value = false;
  submitUpdate();
};

// 更新业务
const submitUpdate = async () => {
  // let params = {} as any;
  if (nodeDefId.value === "ACT_011") {
    // 乙方上传资料
    // params = {
    //   id: formBaseInfo.value.id,
    //   defaultFileList: onFilterFileData(
    //     flowFormData.value.defaultFileList
    //   ),
    //   rectificationInfo: flowFormData.value.rectificationInfo
    // };
    formBaseInfo.value.option = [
      {
        name: "开工材料",
        content: flowFormData.value.defaultFileList,
        type: "files"
      },
      {
        name: "开工材料简述",
        content: flowFormData.value.rectificationInfo,
        type: "textarea"
      }
    ];
  } else {
    // params = {
    //   id: formBaseInfo.value.id,
    //   supervisorAccOpinion: flowFormData.value.supervisorAccOpinion,
    //   content: flowFormData.value.content
    // };
    formBaseInfo.value.option = [
      {
        name: "材料复核",
        content: flowFormData.value.supervisorAccOpinion,
        type: "textarea"
      },
      {
        name: "材料复核意见",
        content: flowFormData.value.content,
        type: "textarea"
      }
    ];
  }
  try {
    // const { code, message } = await snapUpdate(params);
    // if (code === 200) {
    //   toSubmit();
    // } else {
    //   NotifMessage.error(message);
    // }
    toSubmit();
  } catch (err) {
    console.log(err);
  }
};

// 审批
const toSubmit = async () => {
  let nextHandleId = "";
  const info = storageLocal.getItem("info");
  if (lastNode.value === nodeDefId.value) {
    //最后一个节点
    if (formBaseInfo.value.isChargehand === "0") {
      //驳回到指定节点
      // const isValid = await new Promise(resolve =>
      //   rejectFormRef.value.validate(resolve)
      // );
      // if (!isValid) return;
      // formBaseInfo.value.option = [
      //   { name: "reject", content: "#reject#" },
      //   { name: "驳回意见", content: rejectFormData.value.remark }
      // ];
      // nextHandleId = addUserInfo.value?.idList[0]?.id;
      nextHandleId = approveHandlerId.value; //驳回到指定节点时，下一步处理人为指定节点的处理人
    } else {
      nextHandleId = info?.userId;
    }
  } else {
    if (formBaseInfo.value.isChargehand === "0") {
      nextHandleId = approveHandlerId.value;
    } else {
      nextHandleId = addUserInfo.value?.idList[0]?.id;
    }
  }
  let params = {
    formBaseInfo: {
      id: formBaseInfo.value.id,
      acceptUsers: nextHandleId
    },
    flowFormData: {
      businessId: formBaseInfo.value.id,
      flowId: flowId.value,
      flowTypeCode: formBaseInfo.value?.flowMinType || flowType.value,
      instanceId: instanceId.value,
      nodeId: nodeDefId.value,
      projectManageId: storageLocal.getItem("projectInfo")?.id
    },

    formSubMap: {
      flowType: formBaseInfo.value?.flowMinType || flowType.value,
      nodeId: nodeDefId.value,
      procInstId: instanceId.value,
      taskId: formBaseInfo.value?.taskId,
      opinion: JSON.stringify(formBaseInfo.value.option),
      assignee: nextHandleId,
      isChargehand: formBaseInfo.value.isChargehand || "1"
    },

    tmpStorage: {
      nodeId: nodeDefId.value,
      flowId: flowId.value,
      taskId: formBaseInfo.value?.taskId,
      handlerId: nextHandleId,
      userId: info ? info?.userId : "",
      valueJson: JSON.stringify(flowFormData.value)
    }
  };
  try {
    const { code, message } = await startWorkFlowSubmit(params);
    if (code === 200) {
      try {
        _czc.push([
          "_trackEvent",
          "开工通知审批详情",
          "提交",
          `流程审批_${formBaseInfo.value.billName}_${formBaseInfo.value?.flowMinType}`
        ]);
      } catch (err) {
        console.log(err);
      }
      // if (
      //   lastNode.value === nodeDefId.value &&
      //   formBaseInfo.value.isChargehand === "1"
      // ) {
      //   //最后节点，并且选择完成
      //   const resp = await getTableData();
      //   if (resp?.length) {
      //     startFlowNotify(resp);
      //   } else {
      //     NotifMessage.success(message);
      //     emit("handleBack");
      //   }
      // } else {
      //   NotifMessage.success(message);
      //   emit("handleBack");
      // }
      NotifMessage.success(message);
      emit("handleBack");
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

const submitTransfer = async parmas => {
  const info = storageLocal.getItem("info");
  const option = [{ name: "转办", content: "转办协助处理", type: "textarea" }];
  let params = {
    targetAssignee: parmas?.idList[0].id,
    opinion: JSON.stringify(option),
    instanceId: instanceId.value,
    taskId: formBaseInfo.value?.taskId,
    flowId: flowId.value,
    handlerId: info?.userId,
    handlerName: info?.name,
    businessTraParam: {
      id: formBaseInfo.value.id,
      acceptUsers: info?.userId,
      flowType: formBaseInfo.value?.flowMinType || flowType.value
    }
  };
  try {
    const { code, message } = await transfer(params);
    if (code === 200) {
      try {
        _czc.push([
          "_trackEvent",
          "开工通知审批详情",
          "转办",
          `${formBaseInfo.value.billName}_${formBaseInfo.value?.flowMinType}`
        ]);
      } catch (err) {
        console.log(err);
      }
      NotifMessage.success(message);
      emit("handleBack");
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

//发起知会
// const startFlowNotify = async resp => {
//   const info = storageLocal.getItem("info");
//   const notifysAll = resp.map(item => item.userId + "");
//   const notifys = notifysAll.filter(item => {
//     return item != info?.userId;
//   });
//   let params = {
//     assignee: info?.userId,
//     instanceId: instanceId.value,
//     taskId: formBaseInfo.value?.taskId,
//     notifys: notifys
//   };
//   try {
//     const { code, message } = await flowNotify(params);
//     if (code === 200) {
//       NotifMessage.success(message);
//       emit("handleBack");
//     } else {
//       NotifMessage.error(message);
//     }
//   } catch (err) {
//     console.log(err);
//   }
// };

// //获取标段组数据，判断是否存在项目组组长角色
// const getTableData = async () => {
//   try {
//     const { code, data } = await projectTeamList({
//       projectId: storageLocal.getItem("projectInfo")?.id,
//       sectionId: storageLocal.getItem("sectionInfo")?.id,
//       pageNum: 1,
//       pageSize: 10,
//       ext1: "1"
//     });
//     if (code === 200) {
//       const resp = data.list;
//       return resp;
//     }
//   } catch (err) {
//     console.log(err);
//   }
// };

//获取某一节点的处理人
const getApproveUserId = async () => {
  const i = nodeDefId.value == "ACT_015" ? 1 : 0;
  const backNode = flowTypeObj[flowType.value].backNode[i];
  console.log("backNode", backNode, flowTypeObj[flowType.value].backNode);
  const { code, data } = await getApproveHandlerId(instanceId.value, backNode);
  if (code === 200) {
    approveHandlerId.value = data[0];
  } else {
    NotifMessage.error("获取处理人失败");
  }
};

const handleReject = () => {
  dialogVisible.value = true;
};

const handleBack = () => {
  emit("handleBack");
};
watchEffect(() => {
  if (formBaseInfo.value?.taskId) {
    getFlowFormData();
  }
});
watch(
  () => props.formBaseInfo,
  newVal => {
    if (newVal.id) {
      formBaseInfo.value = newVal;
    }
  },
  {
    deep: true,
    immediate: true
  }
);
</script>

<style lang="scss" scoped>
.next-content {
  padding: 10px 20px;
}

:deep(.form__content) {
  .el-form-item--small.el-form-item {
    margin-bottom: 18px;
  }
}
</style>
